<?php
if(!defined('IN_DISCUZ') || !defined('DISCUZ_ROOT')) {
    exit('Access Denied');
}
/**
 * 注册并绑定用户
 * @param array $user_info 用户信息数组
 * @param string $access_token 访问令牌
 * @param string $domain 域名
 * @param object $table_user 用户表对象
 */
function registerAndBindUser($user_info, $access_token, $domain, $table_user) {
    global $_G;
    
    require_once libfile('function/member');
    loaducenter();
    
    // 使用用户昵称作为用户名基础
    $username = $user_info['name'] ?? ('user_'.substr(md5(TIMESTAMP.microtime().rand(1000,9999)), 0, 8));
    
    // 用户名长度检查
    $usernamelen = dstrlen($username);
    if($usernamelen < 3) {
        $username = $username . '_' . random(5);
    }
    
    // 用户名唯一性检查
    while(C::t('common_member')->fetch_by_username($username)) {
        $username = $username . '_' . random(3);
    }

    // 检查用户名是否包含敏感词
    $censorexp = '/^('.str_replace(array('\\*', "\r\n", ' '), array('.*', '|', ''), preg_quote(($_G['setting']['censoruser'] = trim($_G['setting']['censoruser'])), '/')).')$/i';
    if($_G['setting']['censoruser'] && @preg_match($censorexp, $username)) {
        showmessage('profile_username_protect');
        exit;
    }

    // 生成随机密码和设置用户组
    $password = md5(random(10));
    $groupid = $_G['setting']['newusergroupid'];
    
    // 1. 先通过UCenter注册用户
    $uid = uc_user_register(addslashes($username), $password, $user_info['email'], '', '', $_G['clientip']);
    if($uid <= 0) {
        $error_msg = 'UCenter注册失败，';
        switch($uid) {
            case -1: $error_msg .= '用户名不合法'; break;
            case -2: $error_msg .= '包含不允许注册的词语'; break;
            case -3: $error_msg .= '用户名已经存在'; break;
            case -4: $error_msg .= 'Email格式有误'; break;
            case -5: $error_msg .= 'Email不允许注册'; break;
            case -6: $error_msg .= '该Email已经被注册'; break;
            default: $error_msg .= '未知错误';
        }
        showmessage($error_msg, $domain);
        exit;
    }

    // 2. 使用Discuz内置函数完成注册
    $init_arr = array('credits' => explode(',', $_G['setting']['initcredits']));
    C::t('common_member')->insert($uid, $username, $password, $user_info['email'], $_G['clientip'], $groupid, $init_arr);

    // 处理注册IP限制
    if($_G['setting']['regctrl'] || $_G['setting']['regfloodctrl']) {
        C::t('common_regip')->delete_by_dateline($_G['timestamp'] - ($_G['setting']['regctrl'] > 72 ? $_G['setting']['regctrl'] : 72) * 3600);
        if($_G['setting']['regctrl']) {
            C::t('common_regip')->insert(array('ip' => $_G['clientip'], 'count' => -1, 'dateline' => $_G['timestamp']));
        }
    }

    // 绑定聚合账号信息
    // 先查询是否有旧数据，删除旧数据
    $user_info_db = $table_user->fetch_by_erling_unionid($user_info['erling_unionid']);
    if(!empty($user_info_db)){
        $table_user->delete_by_erling_unionid($user_info['erling_unionid']);
    }
    
    $table_user->insert([
        'uid' => $uid,
        'erling_unionid' => $user_info['erling_unionid'],
        'access_token' => $access_token,
        'status' => 1,
        'create_time' => TIMESTAMP,
        'update_time' => TIMESTAMP,
    ]);

    // 自动登录
    $member = getuserbyuid($uid, 1);
    setloginstatus($member, 1296000);
    $formhash = formhash();
    dsetcookie('logout', $formhash, 0, 1);
    
    // 更新注册统计
    include_once libfile('function/stat');
    updatestat('register');
    
    // 跳转到首页
    dheader("Location: $domain");
}


// 回调处理 http://discuz.demo/plugin.php?id=erling_account_center:redirect_callback
// $http = 'http://account-center.cn';
$http = 'https://user.20idc.com';
global $_G;
$uid = $_G['uid'];

$before_type = $_GET['before_type'];
$code = $_GET['code'] ?? '';
$state = $_GET['state'] ?? '';
$appid = $_GET['appid'] ?? '';

$table_user = C::t('#erling_account_center#er_account_user');

// if($before_type == 'register'){
    // 获取配置数据
    $table_connfig = C::t('#erling_account_center#er_account_config');
    $table_connfig_data = $table_connfig->fetch_by_keys(['appid','redirect_url','app_secret']);
    $appid = $table_connfig_data['appid']['value'];
    $domain = $table_connfig_data['redirect_url']['value'];
    $app_secret = $table_connfig_data['app_secret']['value'];
    $redirect_url = $domain.'/plugin.php?id=erling_account_center:redirect_callback';

    // 构建获取 access_token 的 POST 请求数据
    $post_data = array(
        'grant_type' => 'authorization_code',
        'appid' => $appid,
        'app_secret' => $app_secret,
        'code' => $code,
        'redirect_url' => $redirect_url,
    );
    $post_url = $http.'/api/authorize/get/access-token';

    // echo('post_url：'.$post_url.'<br>');
    // echo('post_data：'.json_encode($post_data).'<br>');

    // 发送 POST 请求获取 access_token
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $post_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // 添加以下两行禁用SSL验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($ch);
    curl_close($ch);
    $access_token = json_decode($response, true)['access_token'];
    // echo('access_token：'.$access_token);
    if(empty($access_token)){
        echo('access_token为空');
    }

    // 获取用户信息
    $post_data = array(
        'access_token' => $access_token,
    );
    $post_url = $http.'/api/authorize/get/user-info';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $post_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // 添加以下两行禁用SSL验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($ch);
    curl_close($ch);
    
    $user_info = json_decode($response, true);

    // var_dump($user_info,$access_token);
    // exit;
    
// }


switch ($before_type) {
    case ($before_type=='register_bind'||$before_type=='bind'): // register_bind表示先注册聚合账号然后来直接绑定，bind直接登录后使用登录账号绑定当前网站
        if(empty($_G['uid'])){
            echo('未登录');
            exit;
        }
        // 先检测是否已有erling_unionid绑定账号
        $user_info_db = $table_user->fetch_by_erling_unionid($user_info['erling_unionid']);
        if(!empty($user_info_db)){
            echo('该账号已绑定用户，不可重复绑定');
            exit;
        }
        // 将access_token信息写入数据库
        $table_user->insert([
            'uid' => $uid,
            'erling_unionid' => $user_info['erling_unionid'],
            'access_token' => $access_token,
            'status' => 1,
            'create_time' => TIMESTAMP,
            'update_time' => TIMESTAMP,
        ]);
        // 跳转到 $domain.home.php?mod=spacecp&ac=plugin&op=profile&id=erling_account_center:account_center_user_info
        $url = $domain.'/home.php?mod=spacecp&ac=plugin&op=profile&id=erling_account_center:account_center_user_info';
        // header('Location: '.$url);
        showmessage('绑定成功', $url);

        exit;
    case 'register':// type=register注册新用户
        if(!empty($uid)){
            echo('已有正在登录的账号，注册失败');
            exit;
        }
        registerAndBindUser($user_info, $access_token, $domain, $table_user);
        exit;
    case 'login':// 普通登录，如果当前网站没有绑定的聚合账号，自动注册
        // 判断$user_info['erling_unionid']是否有$table_user匹配的
        if(!empty($uid)){
            echo('已有登录的账号');
            exit;
        }
        $empty_uid = null;
        $user_info_db = $table_user->fetch_by_erling_unionid($user_info['erling_unionid']);
        if(!empty($user_info_db)){
            // 判断discuz中当前用户是否还存在
            $uid = $user_info_db['uid'];
            $member = getuserbyuid($uid);
            if(!empty($member)){
                $empty_uid = $uid;
            }
        }
        if(empty($empty_uid)){
            //  $html = '
            // <style>
            //     .bind-prompt {
            //         position: fixed;
            //         top: 50%;
            //         left: 50%;
            //         transform: translate(-50%, -50%);
            //         width: 400px;
            //         padding: 20px;
            //         background: #fff;
            //         border-radius: 5px;
            //         box-shadow: 0 0 10px rgba(0,0,0,0.2);
            //         text-align: center;
            //         z-index: 9999;
            //     }
            //     .bind-prompt h3 {
            //         margin-top: 0;
            //         color: #333;
            //     }
            //     .bind-buttons {
            //         margin-top: 20px;
            //     }
            //     .bind-buttons button {
            //         padding: 8px 20px;
            //         margin: 0 10px;
            //         border: none;
            //         border-radius: 3px;
            //         cursor: pointer;
            //     }
            //     .btn-confirm {
            //         background: #4CAF50;
            //         color: white;
            //     }
            //     .btn-cancel {
            //         background: #f44336;
            //         color: white;
            //     }
            // </style>
            // <div class="bind-prompt">
            //     <h3>账号未绑定</h3>
            //     <p>没有绑定的Discuz账号，是否自动注册并绑定Discuz账号？</p>
            //     <div class="bind-buttons">
            //         <button class="btn-confirm" onclick="location.href=\'plugin.php?id=erling_account_center:redirect_callback&before_type=register&code='.$code.'&state='.$state.'&appid='.$appid.'\'">是</button>
            //         <button class="btn-cancel" onclick="location.href=\''.$domain.'\'">否</button>
            //     </div>
            // </div>';
            // echo $html;
            registerAndBindUser($user_info, $access_token, $domain, $table_user);
            exit;
        }else{
            // 更新内容
            $uid = $user_info_db['uid'];
            $table_user->update($user_info_db['id'], [
                'access_token' => $access_token,
                'update_time' => TIMESTAMP,
            ]);
            
            // 使用官方登录方式discuz
            require_once libfile('function/member');
            $member = getuserbyuid($uid, 1);
            setloginstatus($member, 1296000);
            $formhash = formhash();
            dsetcookie('logout', $formhash, 0, 1);
            dheader("Location: $domain");
            exit;

            // 手动登录discuz
            // require_once libfile('function/member');
            // $member = getuserbyuid($uid);
            // dsetcookie('auth', authcode("$member[password]\t$member[uid]", 'ENCODE'), 1800);
            // dsetcookie('loginuser');
            // updatecreditbyaction('login', $uid);
            // dsetcookie('stats_qc_login', 3, 86400);

            // C::t('common_member_status')->update($uid, array(
            //     'lastip'=>$_G['clientip'], 
            //     'lastvisit'=>TIMESTAMP, 
            //     'lastactivity' => TIMESTAMP
            // ));
            
            // $ucsynlogin = '';
            // if($_G['setting']['allowsynlogin']) {
            //     loaducenter();
            //     $ucsynlogin = uc_user_synlogin($uid);
            // }
            
            // $param = array(
            //     'username' => $member['username'], 
            //     'usergroup' => $_G['cache']['usergroups'][$member['groupid']]['grouptitle']
            // );
            
            // showmessage('login_succeed', $domain, $param, array('extrajs' => $ucsynlogin));
            
            // 跳转到 $domain
            // $url = $domain;
            // header('Location: '.$url);
            // exit;
        }

        break;
    default:
        # code...
        break;
}

